package com.woniuxy.controller;

import com.woniuxy.entity.Conllection;
import com.woniuxy.service.BlogService;
import com.woniuxy.service.ConllectionService;
import com.woniuxy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/life/conllection")
public class ConllectionController {
    @Autowired
    private ConllectionService conllectionServiceImpl;
    @Autowired
    private BlogService blogServiceImpl;

    /*
    * 添加收藏
    * */
    @PostMapping("/add")
    public ResponseResult<Void> add(@RequestBody Conllection conllection){
        System.out.println("接收到的conllection对象:"+conllection);
        try {
            //收藏，并在该博客的count中加1
            conllectionServiceImpl.add(conllection);
        } catch (Exception e) {
            //如果捕捉到异常则表明触发了数据库中的唯一索引，则应该执行取消收藏的操作（删除）,并在该博客的count中减1
            conllectionServiceImpl.cancel(conllection);
            return ResponseResult.success("取消收藏成功", null);
        }
        return ResponseResult.success("收藏成功", null);
    }

    /*
    * 取消收藏
    * */
    @DeleteMapping("/cancel")
    public ResponseResult<Void> cancel(Conllection conllection){
        conllectionServiceImpl.cancel(conllection);
        return ResponseResult.success("取消收藏成功", null);
    }


    /*
    * 检验是否已经收藏
    * */
    @GetMapping("/check")
    public ResponseResult<Map<String, String>> check(@RequestParam("userId") Integer userId,
                                                     @RequestParam("itemId") Integer itemId){
        System.out.println("userId:::::::::::::::::"+userId+"itemId:::::::::::::::::::::::::::::::"+itemId);
        Conllection number = conllectionServiceImpl.check(userId,itemId);
        //获取blog的 count
        Integer count = blogServiceImpl.getBlogCount(itemId);
        Map<String, String> map = new HashMap<>();
        map.put("count", count.toString());
        // 判断是否为空
        if (number != null){
            map.put("isCollected", String.valueOf(true));
            return ResponseResult.success( "已收藏", map);
        }
        map.put("isCollected", String.valueOf(false));
        return ResponseResult.success("未收藏", map);
    }


    /*
    * 统计用户自己收藏博客的数量
    * */
    @GetMapping("/count")
    public ResponseResult<Integer> count(@RequestParam("userId") Integer userId){
        return ResponseResult.success(conllectionServiceImpl.count(userId));
    }

}
